package cn.com.libertymutual.production.dbconfig;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@MapperScan(basePackages = "cn.com.libertymutual.production.dao.nomorcldatasource", sqlSessionFactoryRef = "nomOrclSqlSessionFactory")
public class NomOrclDSConfig {

	@Autowired
	private Environment env;
	
	@Bean(name = "coreDataOrclDataSource")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        return dataSource;
    }
	
    @Bean(name = "nomOrclSqlSessionFactory")
    public SqlSessionFactory nomOrclSqlSessionFactory(@Qualifier("coreDataOrclDataSource") DataSource dataSource) throws Exception {
    	SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(dataSource);
		
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		factoryBean.setConfiguration(configuration );
		
		factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.nomorcldatasource.type-aliases-package"));
		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
										env.getProperty("mybatis.nomorcldatasource.mapper-locations")));

		return factoryBean.getObject();
    }

    
    @Bean(name = "transactionManagerCoreData")
   	public PlatformTransactionManager primaryTransactionManager(@Qualifier("coreDataOrclDataSource") DataSource dataSource) {
   		return new DataSourceTransactionManager(dataSource);
   	}
}
